/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package persistence;

import entityBeans.Type;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import entityBeans.Recordlevelelement;
import java.util.ArrayList;
import java.util.List;
import persistence.exceptions.NonexistentEntityException;

/**
 *
 * @author allankv
 */
public class TypeJpaController {

    public TypeJpaController() {
        emf = Persistence.createEntityManagerFactory("bdd-javaPU");
    }
    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }

    public Type save(Type type) {
        Type aux = findType(type.getType());
        if(aux==null)
            return create(type);
        else
            return aux;
    }

    public Type create(Type type) {
        Type r = null;
        if (type.getRecordlevelelementList() == null) {
            type.setRecordlevelelementList(new ArrayList<Recordlevelelement>());
        }
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            List<Recordlevelelement> attachedRecordlevelelementList = new ArrayList<Recordlevelelement>();
            for (Recordlevelelement recordlevelelementListRecordlevelelementToAttach : type.getRecordlevelelementList()) {
                recordlevelelementListRecordlevelelementToAttach = em.getReference(recordlevelelementListRecordlevelelementToAttach.getClass(), recordlevelelementListRecordlevelelementToAttach.getIdrecordlevelelement());
                attachedRecordlevelelementList.add(recordlevelelementListRecordlevelelementToAttach);
            }
            type.setRecordlevelelementList(attachedRecordlevelelementList);
            r = em.merge(type);
            for (Recordlevelelement recordlevelelementListRecordlevelelement : type.getRecordlevelelementList()) {
                Type oldTypeOfRecordlevelelementListRecordlevelelement = recordlevelelementListRecordlevelelement.getType();
                recordlevelelementListRecordlevelelement.setType(type);
                recordlevelelementListRecordlevelelement = em.merge(recordlevelelementListRecordlevelelement);
                if (oldTypeOfRecordlevelelementListRecordlevelelement != null) {
                    oldTypeOfRecordlevelelementListRecordlevelelement.getRecordlevelelementList().remove(recordlevelelementListRecordlevelelement);
                    oldTypeOfRecordlevelelementListRecordlevelelement = em.merge(oldTypeOfRecordlevelelementListRecordlevelelement);
                }
            }
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
        return r;
    }

    public void edit(Type type) throws NonexistentEntityException, Exception {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Type persistentType = em.find(Type.class, type.getIdtype());
            List<Recordlevelelement> recordlevelelementListOld = persistentType.getRecordlevelelementList();
            List<Recordlevelelement> recordlevelelementListNew = type.getRecordlevelelementList();
            List<Recordlevelelement> attachedRecordlevelelementListNew = new ArrayList<Recordlevelelement>();
            for (Recordlevelelement recordlevelelementListNewRecordlevelelementToAttach : recordlevelelementListNew) {
                recordlevelelementListNewRecordlevelelementToAttach = em.getReference(recordlevelelementListNewRecordlevelelementToAttach.getClass(), recordlevelelementListNewRecordlevelelementToAttach.getIdrecordlevelelement());
                attachedRecordlevelelementListNew.add(recordlevelelementListNewRecordlevelelementToAttach);
            }
            recordlevelelementListNew = attachedRecordlevelelementListNew;
            type.setRecordlevelelementList(recordlevelelementListNew);
            type = em.merge(type);
            for (Recordlevelelement recordlevelelementListOldRecordlevelelement : recordlevelelementListOld) {
                if (!recordlevelelementListNew.contains(recordlevelelementListOldRecordlevelelement)) {
                    recordlevelelementListOldRecordlevelelement.setType(null);
                    recordlevelelementListOldRecordlevelelement = em.merge(recordlevelelementListOldRecordlevelelement);
                }
            }
            for (Recordlevelelement recordlevelelementListNewRecordlevelelement : recordlevelelementListNew) {
                if (!recordlevelelementListOld.contains(recordlevelelementListNewRecordlevelelement)) {
                    Type oldTypeOfRecordlevelelementListNewRecordlevelelement = recordlevelelementListNewRecordlevelelement.getType();
                    recordlevelelementListNewRecordlevelelement.setType(type);
                    recordlevelelementListNewRecordlevelelement = em.merge(recordlevelelementListNewRecordlevelelement);
                    if (oldTypeOfRecordlevelelementListNewRecordlevelelement != null && !oldTypeOfRecordlevelelementListNewRecordlevelelement.equals(type)) {
                        oldTypeOfRecordlevelelementListNewRecordlevelelement.getRecordlevelelementList().remove(recordlevelelementListNewRecordlevelelement);
                        oldTypeOfRecordlevelelementListNewRecordlevelelement = em.merge(oldTypeOfRecordlevelelementListNewRecordlevelelement);
                    }
                }
            }
            em.getTransaction().commit();
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = type.getIdtype();
                if (findType(id) == null) {
                    throw new NonexistentEntityException("The type with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(Integer id) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Type type;
            try {
                type = em.getReference(Type.class, id);
                type.getIdtype();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The type with id " + id + " no longer exists.", enfe);
            }
            List<Recordlevelelement> recordlevelelementList = type.getRecordlevelelementList();
            for (Recordlevelelement recordlevelelementListRecordlevelelement : recordlevelelementList) {
                recordlevelelementListRecordlevelelement.setType(null);
                recordlevelelementListRecordlevelelement = em.merge(recordlevelelementListRecordlevelelement);
            }
            em.remove(type);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public List<Type> findTypeEntities() {
        return findTypeEntities(true, -1, -1);
    }

    public List<Type> findTypeEntities(int maxResults, int firstResult) {
        return findTypeEntities(false, maxResults, firstResult);
    }

    private List<Type> findTypeEntities(boolean all, int maxResults, int firstResult) {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Type.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
        } finally {
            em.close();
        }
    }

    public Type findType(String q) {
        Query query= getEntityManager().createNamedQuery("Type.findByType");
        query.setParameter("type",q);

        return query.getResultList().isEmpty()?null:(Type)query.getResultList().get(0);
    }
    public Type findType(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Type.class, id);
        } finally {
            em.close();
        }
    }

    public int getTypeCount() {
        EntityManager em = getEntityManager();
        try {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Type> rt = cq.from(Type.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
        } finally {
            em.close();
        }
    }

}
